package com.ergou.easylive.admin.handler;

import com.ergou.easylive.common.entity.response.Result;
import com.ergou.easylive.common.enums.ResultCode;
import com.ergou.easylive.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(BizException.class)
    public Result<Void> handleBizException(BizException e) {
        Integer code = e.getCustomCode() != null ? e.getCustomCode()
                : (e.getResultCode() != null ? e.getResultCode().getCode()
                : ResultCode.BAD_REQUEST.getCode());
        String message = e.getMessage();
        log.warn("业务异常-{}", message);
        return Result.<Void>fail(code, message);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidationException(MethodArgumentNotValidException e) {
        String errorMessage = e.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(error -> error.getField() + ": " + error.getDefaultMessage())
                .collect(Collectors.joining("; "));
        log.error("参数验证失败: {}", errorMessage);
        return Result.<Void>fail(ResultCode.BAD_REQUEST.getCode(), errorMessage);
    }

    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("未处理异常", e);
        return Result.<Void>fail(ResultCode.INTERNAL_SERVER_ERROR);
    }
}
